package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/locales/zh_Hant_TW"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en2 "github.com/go-playground/validator/v10/translations/en"
	zh2 "github.com/go-playground/validator/v10/translations/zh"
)

func Translations() gin.HandlerFunc {
	return func(context *gin.Context) {
		//创建一个多语言翻译器实例，支持英文、简体中文、繁体中文（台湾）
		uni := ut.New(en.New(), zh.New(), zh_Hant_TW.New())
		//获取约定的 Header 参数 locale
		locale := context.GetHeader("locale")
		trans, _ := uni.GetTranslator(locale)
		v, ok := binding.Validator.Engine().(*validator.Validate)
		if ok {
			switch locale {
			case "zh":
				_ = zh2.RegisterDefaultTranslations(v, trans) //将验证器和对应语言类型的 Translator 注册进来
			case "en":
				_ = en2.RegisterDefaultTranslations(v, trans)
			default:
				_ = zh2.RegisterDefaultTranslations(v, trans)
			}
			//设置一个值（interface），可以在下一个函数中，通过 ctx.Get() 取出（interface），取出后需要我们断言
			context.Set("trans", trans)
		}
		context.Next()
	}
}
